<template>
    <div class="table">
        <div class="crumbs">
            <i class="el-icon-tickets"></i>歌单的歌曲信息
        </div>
        <div class="container">
            <div class="handle-box">
                <el-input v-model="params.name" size="mini" placeholder="请输入歌曲名"
                          style="width: 160px;"></el-input>
                <el-button type="primary" size="mini" @click="getList">查询</el-button>
                <el-button type="primary" size="mini" @click="centerDialogVisible=true">添加歌曲</el-button>
                <el-button type="danger" size="mini" @click="deleteHandle()">批量删除</el-button>
            </div>
        </div>
        <el-table size="mini" border width="100px"
                  :data="tableData" @selection-change="selectionChangeHandle">
            <el-table-column
                    type="selection"
                    width="55">
            </el-table-column>
            <el-table-column label="歌曲图片" width="110" align="center">
                <template slot-scope="scope">
                    <div class="song-img">
                        <img :src="getUrl(scope.row.pic)"
                             style="width: 100%" alt="歌曲图片">
                    </div>
                    <div class="play" @click="setSongUrl(scope.row.url,scope.row.name)">
                        <div v-if="toggle === scope.row.name">
                            <span class="icon el-icon-video-pause"></span>
                        </div>
                        <div v-if="toggle !== scope.row.name">
                            <span class="icon el-icon-video-play"></span>
                        </div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="name" label="歌手-歌名" width="120px" align="center"></el-table-column>
            <el-table-column prop="introduction" label="简介" width="150px"></el-table-column>
            <el-table-column label="歌词">
                <template slot-scope="scope">
                    <ul class="lyric">
                        <li v-for="(item,index) in parseLyric(scope.row.lyric)" :key="index">
                            {{item}}
                        </li>
                    </ul>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="150px" align="center">
                <template slot-scope="scope">
                    <!--                    <el-button size="mini" @click="editHandle(scope.row.id)">编辑</el-button>-->
                    <el-button type="danger" size="mini" @click="deleteHandle(scope.row.listSongId)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-dialog title="添加歌曲" :visible.sync="centerDialogVisible" width="400px" center>
            <el-form :model="form" ref="registerForm" label-width="80px" action="" id="tf">
                <!--                <el-form-item prop="singerName" label="歌手名字" size="mini">-->
                <!--                    <el-input v-model="form.singerName" placeholder="歌手名字"></el-input>-->
                <!--                </el-form-item>-->
                <el-form-item prop="songName" label="歌曲名字" size="mini">
                    <!--                    <el-input v-model="form.songName" placeholder="歌曲名字"></el-input>-->
                    <el-select
                            v-model="form.songId"
                            filterable
                            remote
                            reserve-keyword
                            placeholder="请输入关键词"
                            :remote-method="remoteMethod"
                            :loading="loading">
                        <el-option
                                v-for="item in options"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer">
                <el-button size="mini" @click="closeDialog">取消</el-button>
                <el-button size="mini" @click="addSongToSongList">确定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import {mixin} from '../mixins/index'
    import {mapGetters} from 'vuex'
    import '../assets/font/iconfont.css'
    import {addSongToListSong, deleteListSongByIds, getSongInfo, getSongList, listSongDetail} from '../api/index'

    export default {
        mixins: [mixin],
        data() {
            return {
                loading: false,
                centerDialogVisible: false, //添加弹窗是否显示
                songListId: '',
                form: {
                    // singerName: '',     //歌手名字
                    // songName: '',       //歌曲名字
                    songId: ''          //歌曲id
                },
                tableData: [],
                tempData: [],
                params: {},
                dataListSelections: [],
                toggle: '',
                options: [] //搜索时歌曲列表
            }
        },
        computed: {
            ...mapGetters(['isPlay'])
        },
        methods: {
            //查询所有歌曲
            getList() {
                listSongDetail({songListId: this.songListId}).then(({data: res}) => {
                    if (res.code === 0) {
                        this.tableData = []
                        this.tempData = []
                        for (let item of res.data.list) {
                            this.getSong(item.songId, item.id)
                        }
                    } else {
                        this.$message.error('查询失败!请稍后重试')
                    }
                })
            },
            //根据歌曲id查询歌曲对象,放到tempDate和tableData里面
            getSong(songId, listSongId) {
                getSongInfo(songId).then(({data: res}) => {
                    //删除时候所需要的id
                    res.info.listSongId = listSongId
                    this.tableData.push(res.info)
                    this.tempData.push(res.info)
                }).catch(err => {
                        console.log(err)
                    }
                )
            },
            //关闭对话框
            closeDialog() {
                this.centerDialogVisible = false
                // this.$refs.formRef.resetFields()
                //表单项中没有id无法进行
                this.form = {}
            },
            //添加歌曲时候远程搜索歌曲名
            remoteMethod(query) {
                console.log('查询')
                if (query !== '') {
                    this.loading = true
                    getSongList({name: query}).then(({data: res}) => {
                        this.options = res.data.list
                        this.loading = false
                    }).catch((err) => {
                        console.log(err)
                        this.loading = false
                    })
                } else {
                    this.options = []
                }
            },
            //添加歌曲到歌单
            addSongToSongList() {
                //TODO 添加歌单中已经存在的歌曲处理
                var from = {songId: this.form.songId, songListId: this.songListId}
                console.log(from)
                addSongToListSong(from).then(({data: res}) => {
                    if (res.code === 0) {
                        console.log(this.form.songId)
                        //直接查询歌曲并添加到当前队列中
                        //插入成功返回数据
                        this.getSong(this.form.songId, res.data.id)
                        //不使用该方法进行全部查询替换 减轻服务端压力
                        // this.getList()
                        this.$message.success('添加成功')
                        this.closeDialog()
                    }
                })
            },
            //删除处理 根据id(不是歌曲id和歌单id 是他俩确定关系的id)
            deleteHandle(id) {
                console.log(id)
                let ids = id ? [id] : this.dataListSelections.map(item => {
                    return item.listSongId
                })
                this.$confirm(`确定对进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    const {data: res} = await deleteListSongByIds(ids)
                    if (res.code === 0) {
                        this.getList()
                        this.$message.success('删除成功')
                    } else {
                        return this.$message.error('删除失败')
                    }
                }).catch(() => {
                    this.$message.warning('取消删除')
                })
            },
            // 多选值更新
            selectionChangeHandle(val) {
                this.dataListSelections = val
            },
            //解析歌词
            parseLyric(text) {
                let lines = text.split('\n')
                //\d 代表数字 {}代表几个字符 . 任意单字符 ()子正则表达式
                let pattern = /\[\d{2}:\d{2}.(\d{3}|\d{2})\]/g
                let result = []
                for (let item of lines) {
                    let value = item.replace(pattern, '')
                    result.push(value)
                }
                return result
            },
            setSongUrl(url, name) {
                // 触发的是当前歌曲
                if (name === this.toggle) {
                    this.toggle = ''
                    //切换歌曲状态
                    this.$store.commit('setIsPlay', !this.isPlay)
                } else {
                    //设置当前播放音乐状态
                    this.toggle = name
                    //更换歌曲url
                    this.$store.commit('setUrl', url)
                    this.$store.commit('setIsPlay', true)
                }
            }
        },
        created() {
            this.songListId = this.$route.query.id
            this.getList()
        }
    }
</script>

<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }

    .song-img {
        width: 100%;
        height: 100%;
        border-radius: 5px;
        margin-bottom: 5px;
        overflow: hidden;
    }

    .lyric {
        height: 100px;
        overflow-y: scroll;
        overflow-x: hidden;
    }

    /*隐藏滚动条*/
    .lyric::-webkit-scrollbar {
        display: none;
    }

    .play {
        position: absolute;
        z-index: 100;
        width: 80px;
        height: 80px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        top: 18px;
        left: 15px;
    }

    .icon {
        /*width: 4em;*/
        /*height: 3em;*/
        border-color: red;
        font-size: 30px !important;
        color: white;
        fill: currentColor;
        overflow: hidden;
    }
</style>